import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import {
  logout,
  fetchCaptcha,
  fetchUserInfo, loginUser, addUserThunk, userDeleteAgentsThunk, userAddAgentsThunk, updateUserThunk,
} from '@/services/userService';
import { setToken, clearToken } from '@/utils/auth';
import {UserInfo, UserState} from "@/types/userType";


const initialState: UserState = {
    user: null,
    captcha: '',
    status: 'idle',
    error: null,
};

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers:{
        // Reset announcement information
        resetUserInfo: (state) => {
            state.user = null;
            state.captcha = '';
            state.status = 'idle';
            state.error = null;
        },
        // Set partial announcement information
        setUserInfo: (state, action: PayloadAction<Partial<UserInfo>>) => {
            if (state.user) {
              console.log(action.payload)
                state.user = { ...state.user, ...action.payload };
            }
        },
    },
    extraReducers: (builder) => {
        // Handle login
        builder
            .addCase(loginUser.fulfilled, (state, action) => {
                state.status = 'succeeded';
                setToken(action.payload.access_token);
                state.user = action.payload.user;
            })
            .addCase(loginUser.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Handle logout
        builder
            .addCase(logout.fulfilled, (state) => {
                state.status = 'succeeded';
                state = initialState;
                clearToken();
            });

        // Handle captcha fetching
        builder
            .addCase(fetchCaptcha.fulfilled, (state, action) => {
                state.captcha = `data:image/png;base64, ${action.payload.image}`;
                state.status = 'succeeded';
            })
            .addCase(fetchCaptcha.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Handle fetching user info
        builder
            .addCase(fetchUserInfo.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.user = action.payload
            })
            .addCase(fetchUserInfo.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Add user agent
        builder
          .addCase(addUserThunk.pending, (state) => {
            state.status = 'loading';
          })
          .addCase(addUserThunk.fulfilled, (state, action) => {
            state.status = 'succeeded';
            console.log("user update")
            console.log(action.payload);
          })
          .addCase(addUserThunk.rejected, (state, action) => {
            state.status = 'failed';
            state.error = action.payload as string;
          });

      // update user info
      builder
        .addCase(updateUserThunk.pending, (state) => {
          state.status = 'loading';
        })
        .addCase(updateUserThunk.fulfilled, (state, action) => {
          state.status = 'succeeded';
          setUserInfo(action.payload);
        })
        .addCase(updateUserThunk.rejected, (state, action) => {
          state.status = 'failed';
          state.error = action.payload as string;
        });

      builder
        .addCase(userDeleteAgentsThunk.pending, (state) => {
          state.status = 'loading';
        })
        .addCase(userDeleteAgentsThunk.fulfilled,  (state, action) => {
          state.status = 'succeeded';
          if (state.user) {
            state.user.add_agents = state.user.add_agents.filter(
              (agent) => !action.payload.agent_uuids.includes(agent.uuid)
            );
          }
        })
        .addCase(userDeleteAgentsThunk.rejected, (state, action) => {
          state.status = 'failed';
          state.error = action.payload as string;
        });

      builder
        .addCase(userAddAgentsThunk.pending, (state) => {
          state.status = 'loading';
        })
        .addCase(userAddAgentsThunk.fulfilled,  (state, action) => {
          state.status = 'succeeded';
          if (state.user)
              state.user.add_agents = action.payload;
        })
        .addCase(userAddAgentsThunk.rejected, (state, action) => {
          state.status = 'failed';
          state.error = action.payload as string;
        });

    },
});

export const { resetUserInfo, setUserInfo } = userSlice.actions;

export default userSlice.reducer;
